package ybl.wechat;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONObject;

import java.io.IOException;

public class WeChatUtils {
    private static final OkHttpClient client = new OkHttpClient();

    /**
     * 执行HTTP请求并返回结果。
     *
     * @param url 请求的URL
     * @return 请求的结果，表示为一个JSONObject
     */
    public static JSONObject executeRequest(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return new JSONObject(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 执行HTTP请求并返回JSONObject。
     *
     * @param request 请求对象
     * @return 响应的JSONObject
     * @throws IOException  当发生网络错误时
     * @throws ApiException 当API返回错误时
     */
    public static JSONObject executeRequest(Request request) throws IOException, ApiException {
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful())
                throw new IOException("Unexpected code " + response);

            String responseBody = response.body().string();
            JSONObject jsonObject = new JSONObject(responseBody);
            if (jsonObject.optInt("errcode", 0) != 0) {
                throw new ApiException("API Error: " + jsonObject.optString("errmsg", responseBody));
            }
            return jsonObject;
        }
    }
}
